const crypto = require('crypto');


//md5加密 使用
// 可任意多次调用update():
const hash = crypto.createHash('md5');  //md5改为sha1就是sha1加密
hash.update('Hello, world!');
hash.update('Hello, nodejs!');//update的功能是更新

console.log('md5加密算法:'+hash.digest('hex'));//以16进制方式输出


//hmac 可以使用md5和 sha1等算法加密，同时也需要一个密钥
const hmac = crypto.createHmac('sha256', 'tsqlpky'); //tsqlpky就是密钥
hmac.update("hello, world!");
hmac.update("hello, nodejs!");

console.log('hmac加密算法:'+hmac.digest('hex'));

//AES加密算法
//封装加密函数
function aesEncrypt(data,key)   //key作为密钥
{
    const cipher=crypto.createCipher("aes192",key);
    var crypted=cipher.update(data,'utf8','hex');
    crypted +=cipher.final('hex');

    return crypted;
}
//封装加密算法
function aesDecrypt(encrypted,key)//key是密钥
{
    const decipher=crypto.createDecipher('aes192',key);
    var decrypted=decipher.update(encrypted,"hex","utf8");
    decrypted+=decipher.final("utf8");

    return decrypted;
}
var data='Hello,this is a secret massage!';
var key='tsqpky';
var encrypted=aesEncrypt(data,key);
var decrypted=aesDecrypt(encrypted,key);

console.log('AES加密算法-------------------------');
console.log("Plain text: "+data);
console.log("Encrypted text: "+encrypted);
console.log("Decrypted text: "+decrypted);
